<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class ValidDragonSheet implements FromCollection, WithTitle, WithColumnWidths
{
    private $row;
    private $data;

    public function __construct($row, $data)
    {
        $this->row  = $row;
        $this->data = $data;
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $row  = $this->row;
        $data = $this->data;
        //设置表头
        foreach ($row[0] as $key => $value) {
            $key_arr[] = $key;
        }

        //输入数据
        foreach ($data as $key => &$value) {
            $js = [];
            for ($i = 0; $i < count($key_arr); $i++) {
                $js = array_merge($js, [$key_arr[$i] => $value[$key_arr[$i]]]);
            }
            array_push($row, $js);
            unset($val);
        }
        return collect($row);

    }

    public function title(): string
    {
        return '有效接龙订单数据';
    }


    public function columnWidths(): array
    {
        $widths = [];
        $index  = 1;
        foreach ($this->row[0] as $value) {
            if ($index == 1) {
                $widths['A'] = 10;
                $index++;
                continue;
            }
            $columnIndex          = Coordinate::stringFromColumnIndex($index);
            $length               = mb_strlen($value);
            $widths[$columnIndex] = $length > 6 ? $length + 30 : 20;
            $index++;
        }
        return $widths;
    }
}
